package wy.RabbitMqDemo.consumer;

import java.io.IOException;
import java.util.Map;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;

import wy.RabbitMqDemo.entity.Order;

@Component
public class OrderReciver {

	/**
	 * @RabbitListener 消息监听，可配置交换机、队列、路由key 该注解会创建队列和交互机 并建立绑定关系
	 * @RabbitHandler 标识此方法如果有消息过来，消费者要调用这个方法
	 * @Payload 消息体
	 * @Headers 消息头
	 * @param order
	 */
	@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "${spring.rabbitmq.listener.order.queue.name}", durable = "${spring.rabbitmq.listener.order.queue.durable}"), exchange = @Exchange(name = "${spring.rabbitmq.listener.order.exchange.name}", durable = "${spring.rabbitmq.listener.order.exchange.durable}", type = "${spring.rabbitmq.listener.order.ecchange.type}"), key = "${spring.rabbitmq.listener.order.key}"))
	@RabbitHandler
	public void onOrderMessage(@Payload Order order, @Headers Map<String, Object> headers, Channel channel)
			throws IOException {
		// 消费者操作
		System.out.println("------收到消息，开始消费-----");
		System.out.println("订单id：" + order.getId());

		Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

		// ACK
		channel.basicAck(deliveryTag, false);

	}

}
